package com.zaozhuang.robot.schedulerequest;

import static com.zaozhuang.robot.QrCodeActivity.ROBOT_PERSON_API;
import static com.zaozhuang.robot.QrCodeActivity.WX_APP_ID;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.zaozhuang.robot.request.PersonCheckQRCodeResultRequestBean;
import com.zaozhuang.robot.request.PersonCheckQRCodeResultResponseBean;
import com.zaozhuang.robot.request.PersonCheckResultRequestBean;
import com.zaozhuang.robot.request.PersonCheckResultResponseBean;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PeriodicRequestTask {
    private OnPeriodicRequestStopListener onPeriodicRequestStopListener;
    private static final int MAX_ATTEMPTS = 40; // 最大尝试次数
    private static final long INTERVAL_MS = 3000; // 每隔 3 秒

    private int attemptCount = 0; // 当前尝试次数
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable requestRunnable;
    private Gson gson = new Gson();
    private OkHttpClient client = new OkHttpClient();

    private PeriodicRequestTask(){}

    public PeriodicRequestTask(OnPeriodicRequestStopListener onPeriodicRequestStopListener) {
        this.onPeriodicRequestStopListener = onPeriodicRequestStopListener;
    }

    public void startPeriodicCheckQRCodeRequests(String reqid) {
        requestRunnable = () -> {
            if (attemptCount >= MAX_ATTEMPTS) {
                stopPeriodicRequests(false);
                return;
            }

            attemptCount++;

            // 发起网络请求
            requestQRCodeCheckResult(reqid, result -> {
                if ("2".equals(result)) { //请求二维码方式
                    // 如果满足条件，停止任务
                    stopPeriodicRequests(true);
                    handler.removeCallbacks(requestRunnable);
                } else {
                    scheduleNextRequest();
                }
            });
        };

        scheduleNextRequest();
    }

    public void startPeriodicCheckPersonRequests(String reqid) {
        requestRunnable = () -> {
            if (attemptCount >= MAX_ATTEMPTS) {
                stopPeriodicRequests(false);
                return;
            }

            attemptCount++;

            // 发起网络请求
            requestCheckPersonCheckResult(reqid, result -> {
                if ("1".equals(result)) { //启动小程序方式
                    // 如果满足条件，停止任务
                    stopPeriodicRequests(true);
                    handler.removeCallbacks(requestRunnable);
                } else {
                    scheduleNextRequest();
                }
            });
        };

        scheduleNextRequest();
    }

    private void scheduleNextRequest() {
        handler.postDelayed(requestRunnable, INTERVAL_MS);
    }

    //供外部使用，比如对话框手动关闭的时候，页面关闭的时候
    public void stopPeriodic(){
        handler.removeCallbacks(requestRunnable);
    }
    private void stopPeriodicRequests(boolean isSuccess) {
        if (onPeriodicRequestStopListener != null) {
            onPeriodicRequestStopListener.onPeriodicRequestStop(isSuccess);
        }
        handler.removeCallbacks(requestRunnable);
        Log.e("PeriodicRequestTask", "任务已停止");
    }

    private void requestQRCodeCheckResult(String reqid, OnRequestCompleteListener listener) {
        PersonCheckQRCodeResultRequestBean bean = new PersonCheckQRCodeResultRequestBean(
                "robot",
                "getqrresult",
                "调用小程序的 APPID",
                reqid);

        PersonCheckQRCodeResultRequestBean beanTest = new PersonCheckQRCodeResultRequestBean(
                "robot",
                "getqrresult",
                WX_APP_ID,
                reqid);
        String json = gson.toJson(beanTest);
        Log.e("qrcode 请求核验参数 json", "" +json);
        Log.e("requestCheckPersonCheckResult", "json = " +json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(ROBOT_PERSON_API)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Toast.makeText(QrCodeActivity.this, "请求人脸核验结果出错", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
                scheduleNextRequest();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string();
                        PersonCheckQRCodeResultResponseBean bean = gson.fromJson(result, PersonCheckQRCodeResultResponseBean.class);
                        Log.e("qrcode 请求核验结果 json", "" +result);
                        if (bean == null || bean.getErrcode() != 0) {
                            // 处理错误情况
                            Log.e("requestQRCodeCheckResult", "请求失败: " + bean.getErrmsg());
                        } else {
                            // 获取状态并通知回调
                            String status = bean.getData().getStatus();
                            listener.onComplete(status);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 异常处理
                        Log.e("requestQRCodeCheckResult", "解析响应失败");
                    }
                } else {
                    // 处理错误情况
                    Log.e("requestQRCodeCheckResult", "响应失败: " + response.code());
                }
            }
        });
    }

    /**
     * 网络请求方法
     */
    private void requestCheckPersonCheckResult(String reqid, OnRequestCompleteListener listener) {
        PersonCheckResultRequestBean bean = new PersonCheckResultRequestBean(
                "robot",
                "getresult",
                "调用小程序的 APPID",
                "调用路径格式为`pages/certification/byrobot/cert_{id}`，`id`取值 1 - 9 且与设备 ID 对应",
                reqid);
        PersonCheckResultRequestBean beanTest = new PersonCheckResultRequestBean(
                "robot",
                "getresult",
                WX_APP_ID,
                "pages/certification/byrobot/cert_1",
                reqid);

        String json = gson.toJson(beanTest);
        Log.e("requestCheckPersonCheckResult", "json = " + json);

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(ROBOT_PERSON_API)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 请求失败时，继续下一次请求
                scheduleNextRequest();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        PersonCheckResultResponseBean bean = gson.fromJson(response.body().string(), PersonCheckResultResponseBean.class);
                        if (bean == null || bean.getErrcode() != 0) {
                            // 处理错误情况
                            Log.e("requestCheckPersonCheckResult", "请求失败: " + bean.getErrmsg());
                        } else {
                            // 获取状态并通知回调
                            String status = bean.getData().getStatus();
                            listener.onComplete(status);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 异常处理
                        Log.e("requestCheckPersonCheckResult", "解析响应失败");
                    }
                } else {
                    // 处理错误情况
                    Log.e("requestCheckPersonCheckResult", "响应失败: " + response.code());
                }
            }
        });
    }

    /**
     * 回调接口，用于处理请求结果
     */
    private interface OnRequestCompleteListener {
        void onComplete(String result);
    }

    public interface OnPeriodicRequestStopListener {
        void onPeriodicRequestStop(boolean isSuccess);
    }
}